﻿using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain.AUTH;
using OpenAuth.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace OpenAuth.App.AUTH
{
    /// <summary>
    /// 用户
    /// </summary>
    public class Auth_UserApp :BaseApp<Auth_User, OpenAuthDBContext>
    {
        private DbExtension _dbExtension;

        public async Task<TableData> Load(Auth_UserListReq request) {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }
            var result = new TableData();
            var obj = UnitWork.Find<Auth_User>(null);
            var User_Org = UnitWork.Find<Auth_Org_Info>(null);

            if (!string.IsNullOrEmpty(request.key))
            {
                obj= obj.Where(u => u.Account.Contains(request.key)||u.Name.Contains(request.key));
            }
            /*
              var org = loginUser.Orgs.SingleOrDefault(u => u.Id == request.orgId);
                var cascadeId = org.CascadeId;
                
                var orgIds = loginUser.Orgs.Where(u => u.CascadeId.Contains(cascadeId)).Select(u => u.Id).ToArray();
            
                //只获取机构里面的用户
                userOrgs = userOrgs.Where(u => u.Key == Define.USERORG && orgIds.Contains(u.OrgId));
             */
            var orgid = GetSons(User_Org.ToList(), request.ORG_ID).Select(u => u.Id).ToList();
            if (!string.IsNullOrEmpty(request.ORG_ID)) {
               
               // obj = obj.Where(u=>u.ORG_ID.Contains( string.Join(',', orgid, request.ORG_ID)));
                obj = obj.Where(u=>u.ORG_ID.Contains(request.ORG_ID)|| orgid.Contains(u.ORG_ID));
                
            }
            result.count = obj.Count();
           // result.data = obj.Skip((request.page - 1) * request.limit).Take(request.limit).ToList();

            var userOrgs = from user in obj
                           join
          orginfo in UnitWork.Find<Auth_Org_Info>(null)
          on user.ORG_ID equals orginfo.Id
                           select new
                           {
                               user.Account,
                               user.Name,
                               ORGNAME = orginfo.ORG_NAME,
                               user.Id
                           };
            result.data= userOrgs.Skip((request.page - 1) * request.limit).Take(request.limit).ToList();
            return result;
            // result.columnHeaders =
            //var userOrgs = from user in obj
            //               where user.ORG_ID==string.Join(',', orgid)
            //               select new
            //               {
            //                   user.LOGINNAME,
            //                   user.USER_CODE,

            //               };
            /*
             var userOrgs = from user in query
                join relevance in UnitWork.Find<Relevance>(u =>u.Key=="UserOrg")
                    on user.Id equals relevance.FirstId into temp
                from r in temp.DefaultIfEmpty()
                join org in UnitWork.Find<Org>(null)
                    on r.SecondId equals org.Id into orgtmp
                from o in orgtmp.DefaultIfEmpty()
                select new
                {
                    user.Account,
                    user.Name,
                    user.Id,
                    user.Sex,
                    user.Status,
                    user.BizCode,
                    user.CreateId,
                    user.CreateTime,
                    user.TypeId,
                    user.TypeName,
                    r.Key,
                    r.SecondId,
                    OrgId = o.Id,
                    OrgName= o.Name
                };
             */



        }
        #region 获取所有下级
        public static IEnumerable<Auth_Org_Info> GetSons(IList<Auth_Org_Info> list, string Fid)
        {
            var query = list.Where(p => p.Id == Fid).ToList();
            var list2 = query.Concat(GetSonList(list, Fid));
            return list2;
        }

        public static IEnumerable<Auth_Org_Info> GetSonList(IList<Auth_Org_Info> list, string Fid)
        {
            var query = list.Where(p => p.PARENT_ID == Fid).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.Id)));
        }
        #endregion

        #region 获取所有上级
        public static IEnumerable<Auth_Org_Info> GetFatherList(IList<Auth_Org_Info> list, string Id)
        {
            var query = list.Where(p => p.Id == Id).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetFatherList(list, t.PARENT_ID)));
        }
        #endregion

        public Auth_UserApp(IUnitWork<OpenAuthDBContext> unitWork, IRepository<Auth_User, OpenAuthDBContext> repository, IAuth auth,
           RevelanceManagerApp revelanceApp, DbExtension dbExtension) : base(unitWork, repository, auth)
        {
            _dbExtension = dbExtension;
        }
    }
}
